package com.longrise.android.byjk.plugins.poster.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.loadmore.LoadMoreView;
import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.byjk.R;
import com.longrise.android.byjk.common.UrlConstants;
import com.longrise.android.byjk.plugins.poster.PosterListActivity;
import com.longrise.android.byjk.plugins.poster.adapter.PosterListAdapter;
import com.longrise.android.byjk.plugins.poster.bean.ImageBean;
import com.longrise.android.byjk.plugins.poster.posterdetail.PosterDetailActivity;
import com.longrise.android.byjk.plugins.poster.posterdetail.assist.ImgList;
import com.longrise.android.byjk.plugins.poster.presenter.PosterDataPresenter;
import com.longrise.android.byjk.plugins.poster.presenter.PosterDataView;
import com.longrise.android.byjk.widget.view.BBswipeRefreshLayout;
import com.longrise.android.loaddata.newloaddata.LoadDataManagerFather;
import com.longrise.common.base.BaseFragment;
import com.longrise.common.datasource.remote.LoadDataManager;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/9/27.
 */

public class PosterListFragment extends BaseFragment<PosterDataPresenter> implements SwipeRefreshLayout.OnRefreshListener, PosterListAdapter.OnPosterItemClickListener
        , BaseQuickAdapter.RequestLoadMoreListener, PosterDataView {

    private static final String TAG = "PosterListFragment";

    private RecyclerView rcv_poster;
    private PosterListAdapter mAdapter;
    private String type, areaname;
    private List<ImageBean> imageList = new ArrayList<>();
    private List<ImageBean> list = new ArrayList<>();
    private boolean mIsVisibleToUser = false;
    private boolean mViewCreated = false;
    private int mPageNum;
    private int mSinglepageNum = 15;  //单次请求获取的item数量
    private int mCurrentBeansLen;
    private boolean isFirstLoaded = false; //页面第一次有没有重新加载过数据
    private BBswipeRefreshLayout mBbsrl;
    private int num;


    public static PosterListFragment newInstance(String type, String areaname, int i) {
        PosterListFragment fragment = new PosterListFragment();
        Bundle bundle = new Bundle();
        bundle.putString("type", type);
        bundle.putString("areaname", areaname);
        bundle.putInt("num", i);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        mIsVisibleToUser = isVisibleToUser;
        if (mViewCreated && mIsVisibleToUser) {
            getFirstData(1, false);
        }
    }

    @Override
    protected int getLayoutResourse(@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_hot_poster;
    }

    @Override
    public void initView() {
        mViewCreated = true;
        type = getArguments().getString("type");
        areaname = getArguments().getString("areaname");
        num = getArguments().getInt("num");
        rcv_poster = (RecyclerView) mRootView.findViewById(R.id.rcv_poster);
        mBbsrl = (BBswipeRefreshLayout) mRootView.findViewById(R.id.brl_poster);
        mBbsrl.setOnRefreshListener(this);
        initAdapter();

        if (mIsVisibleToUser) {
            getFirstData(1, false);
        }
    }


    private void initAdapter() {
        mAdapter = new PosterListAdapter();
        mAdapter.setOnLoadMoreListener(this);
        mAdapter.setOnRcvItemClickListener(this);
        mAdapter.setLoadMoreView(new LoadMoreView() {
            @Override
            public int getLayoutId() {
                return R.layout.item_loadmore_view;
            }

            @Override
            protected int getLoadingViewId() {
                return R.id.load_more_loading_view;
            }

            @Override
            protected int getLoadFailViewId() {
                return R.id.load_more_load_fail_view;
            }

            @Override
            protected int getLoadEndViewId() {
                return R.id.load_more_load_end_view;
            }
        });
        final GridLayoutManager layoutManager = new GridLayoutManager(mContext, 3, GridLayoutManager.VERTICAL, false);
        rcv_poster.setLayoutManager(layoutManager);
        rcv_poster.setAdapter(mAdapter);
    }

    private void getFirstData(int pageNum, boolean isLoadMore) {
        if (!isFirstLoaded) {
            ImgList.getInstance().clearAll();
            imageList.clear();
            list.clear();
            mAdapter.notifyDataSetChanged();
            getData(pageNum, isLoadMore);
            isFirstLoaded = true;
        } else {
            ImgList.getInstance().clearAll();
            if (list != null && list.size() > 0) {
                ImgList.getInstance().addAll(list);
            } else {
                getData(pageNum, isLoadMore);
            }
        }
    }

    /**
     * 获取展示的数据
     */
    private void getData(int pageNum, final boolean isLoadMore) {
        mBbsrl.setRefreshing(true);
        mPageNum = pageNum;
        EntityBean bean = new EntityBean();
        bean.set("goodstype", type);
//        bean.set("pagenum", mPageNum);
        bean.set("pagenum", -1);
        bean.set("pagesize", mSinglepageNum);
        EntityBean fbean = new EntityBean();
        fbean.set("bean", bean);
        LoadDataManager.getInstance().callService2(null, UrlConstants.BaseUrl, "bbt_vip_sPostersInfoBygoodstype", fbean, new LoadDataManager.OnRequestCallListener2() {

            @Override
            public void onSuccess(String key, String service, Object result) {
                try {
                    EntityBean bean = (EntityBean) result;
                    parseResult(bean, isLoadMore);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }


            @Override
            public void onFinished(String key, String service) {
                mBbsrl.setRefreshing(false);
            }

            @Override
            public void onError(String key, String service, LoadDataManagerFather.ResultType resultType) {
                mBbsrl.setRefreshing(false);
            }


        });
    }

    private void parseResult(EntityBean bean, boolean isLoadMore) {
        String resultdesc = bean.getString("resultdesc");
        int value = (Integer) bean.get("resultstate");
        if (value == 1) {
            EntityBean[] beans = bean.getBeans("result");
            if (beans == null) {
                mCurrentBeansLen = 0;
                beans = new EntityBean[]{};
            } else {
                mCurrentBeansLen = beans.length;
            }
            if (isLoadMore) {
                imageList.clear();
            }
            for (int i = 0; i < beans.length; i++) {
                String goodsid = beans[i].getString("id");
                String backpicurl = beans[i].getString("backpicurl");
                String showpicurl = beans[i].getString("showpicurl");
                String detailpicurl = beans[i].getString("detailpicurl");
                String needscore = beans[i].getString("needscore");
                String areaname = beans[i].getString("areaname");
                String rankvalue = beans[i].getString("rankvalue");
                String showsharenum = beans[i].getString("showsharenum");
                String isnew = beans[i].getString("isnew");
                ImageBean imageBean = new ImageBean();
                imageBean.setAreaname(areaname);
                imageBean.setGoodsid(goodsid);
                imageBean.setBackpicurl(backpicurl);
                imageBean.setDetailpicurl(detailpicurl);
                imageBean.setShowsharenum(showsharenum);
                imageBean.setIsnew(isnew);
                imageBean.setRankvalue(rankvalue);
                imageBean.setNeedscore(needscore);
                imageBean.setShowpicurl(showpicurl);
                imageList.add(imageBean);
            }
            list.addAll(imageList);
            mAdapter.setDatas(imageList, isLoadMore);
            mAdapter.notifyDataSetChanged();
            ImgList.getInstance().addAll(imageList);
            mAdapter.loadMoreEnd();
//            if (isLoadMore) {
//                mAdapter.loadMoreComplete();
//            }
//            if (mCurrentBeansLen < mSinglepageNum) {
//                mAdapter.loadMoreEnd();
//            }
        } else {
            mCurrentBeansLen = 0;
            showToast(resultdesc);
            if (isLoadMore) {
                mAdapter.loadMoreFail();
            }
        }
    }

    @Override
    public void onClick(int position) {
        Intent intent = new Intent(getActivity(), PosterDetailActivity.class);
        intent.putExtra(PosterDetailActivity.EXTRA_TAG_NAME, areaname);
        intent.putExtra(PosterDetailActivity.EXTRA_CURRENT_POSITION, position);
        intent.putExtra(PosterDetailActivity.EXTRA_TAG_TYPE, type);
        startActivity(intent);
        ((PosterListActivity)getContext()).overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
    }

    @Override
    public void onLoadMoreRequested() {
//        if (mCurrentBeansLen < mSinglepageNum) {
//            //mAdapter.loadMoreEnd(false);
//        } else {
//            getData(mPageNum + 1, true);
//        }
//        getData(mPageNum + 1, true);
    }

    @Override
    public void onRefresh() {
        isFirstLoaded = false;
        getFirstData(1, false);
    }


    @Override
    public void showData(EntityBean[] beans) {

    }

    @Override
    public void showLoadingDialog() {

    }

    @Override
    public void dismissLoadingDialog() {

    }
}
